package com.xywy.start;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xywy.R;
import com.xywy.common.FragmentMainActivity;
import com.xywy.common.bean.ConnectedDevice;
import com.xywy.common.constants.ResultCode;
import com.xywy.common.greendao.BaseDao;
import com.xywy.common.manager.AppManager;
import com.xywy.common.net.AsyncHttpClient;
import com.xywy.common.net.OnResultListenerAdapter;
import com.xywy.common.net.Parser;
import com.xywy.common.sync.SyncBloodPresureDevice;
import com.xywy.common.sync.SyncWeightScaleData;
import com.xywy.common.util.FileUtil;
import com.xywy.common.util.MLog;
import com.xywy.common.widget.MyProgress;
import com.xywy.me.SetupAcValMobileActivity;
import com.xywy.me.bean.User;
import com.xywy.me.bean.UserKeeper;
import com.xywy.wjk.bean.BloodPressureData;
import com.xywy.wjk.bean.WeightData;
import com.xywy.wjk.dao.BloodPressureDataDao;
import com.xywy.wjk.dao.WeightDataDao;

/**
 * 启动页
 * 
 * @author xiaogd
 * 
 */
public class MainActivity extends Activity {
	private static int WAIT_FOR = 1;
	private TextView login;
	private String mobile;
	private String password;
//	private String userid; // 临时先用userid判断
	private ViewPager slidingLayout;
	private List<ImageView> images = new ArrayList<ImageView>();
	private ImageView firstDot,secondDot,thiredDot;
	private AppManager appManager;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置为全屏
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		appManager = AppManager.getInstance();
		appManager.addActivity(this);
		preInit();
		
		// 利用handler来使主线程睡眠一段时间
		SharedPreferences sp = getSharedPreferences("config",
				Context.MODE_PRIVATE);
		mobile = sp.getString("mobile", "null");
		password = sp.getString("password", "null");
//		userid = sp.getString("userid", "null");
		int i = getIntent().getIntExtra("source", 0);
		/**
		 * 加那个默认的消息提醒
		 */
		
		if (i == 0) {
			handler.sendEmptyMessage(WAIT_FOR);
		}
		User current_user = UserKeeper.getCurrentUser(this);
		/*if (!"null".equals(userid) && !"".equals(userid)) {
			// sendMsg();
			Intent intent = new Intent(this, FragmentMainActivity.class);
			this.startActivity(intent);
			finish();
		} */
		if(current_user != null){
				// sendMsg();
			Intent intent = new Intent(this, FragmentMainActivity.class);
			this.startActivity(intent);
			finish();
		}else {
			setTheme(R.style.main);
			setContentView(R.layout.start_main);
			slidingLayout = (ViewPager) findViewById(R.id.slidingLayout);
			initPager();
			// btStartLogin();
		}
		
	}

	private void initPager() {
		// TODO Auto-generated method stub
		ImageView firstImg = new ImageView(this);
		firstImg.setImageResource(R.drawable.image1);
		ImageView secondImg = new ImageView(this);
		secondImg.setImageResource(R.drawable.image2);
		ImageView thiredImg = new ImageView(this);
		thiredImg.setImageResource(R.drawable.image3);
		images.add(firstImg);
		images.add(secondImg);
		images.add(thiredImg);
		
		firstDot = (ImageView) findViewById(R.id.firstDot);
		secondDot = (ImageView) findViewById(R.id.secondDot);
		thiredDot = (ImageView) findViewById(R.id.thiredDot);
		
		slidingLayout.setAdapter(new PagerAdapter() {
			
			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return images.size();
			}
			
			// 来判断显示的是否是同一张图片，这里我们将两个参数相比较返回即可
			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				// TODO Auto-generated method stub
				return arg0 == arg1;
			}
			@Override
			public void destroyItem(ViewGroup view, int position, Object object) {
			view.removeView(images.get(position));
			}
			 
			// 当要显示的图片可以进行缓存的时候，会调用这个方法进行显示图片的初始化，我们将要显示的ImageView加入到ViewGroup中，然后作为返回值返回即可
			@Override
			public Object instantiateItem(ViewGroup view, int position) {
			view.addView(images.get(position));
			return images.get(position);
			}
		});
		
		slidingLayout.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				// TODO Auto-generated method stub
				setImageSelect(position);
			}
			

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	

	private void setImageSelect(int position) {
		// TODO Auto-generated method stub
		 switch (position) {
		case 0:
			firstDot.setImageResource(R.drawable.start_dot_selected);
			secondDot.setImageResource(R.drawable.start_dot_unselected);
			thiredDot.setImageResource(R.drawable.start_dot_unselected);
			break;
		case 1:
			firstDot.setImageResource(R.drawable.start_dot_unselected);
			secondDot.setImageResource(R.drawable.start_dot_selected);
			thiredDot.setImageResource(R.drawable.start_dot_unselected);
			break;
		case 2:
			firstDot.setImageResource(R.drawable.start_dot_unselected);
			secondDot.setImageResource(R.drawable.start_dot_unselected);
			thiredDot.setImageResource(R.drawable.start_dot_selected);
			break;

		default:
			break;
		}
	}
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == WAIT_FOR) {
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	};

	public void startOnClick(View view) {
		switch (view.getId()) {
		case R.id.bt_start_experience:
			btStartExperience();
			break;
		case R.id.bt_start_main_login:
			btStartLogin();
			break;
		}
		;
	}

	private void btStartExperience() {
		Intent intent = new Intent(this, HeightActivity.class);
		startActivity(intent);
	}

	private void btStartLogin() {
		Intent intent = new Intent(this, LoginActivity.class);
		startActivity(intent);
		finish();
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	public void preInit() {
		ConnectedDevice weight_device = FileUtil.getWeightDevice();
		ConnectedDevice blood_device = FileUtil.getBloodDevice();
		ConnectedDevice temp_device = FileUtil.getTemputerDevice();
		weight_device.setConnected(false);
		blood_device.setConnected(false);
		temp_device.setConnected(false);
		FileUtil.saveBloodDevice(blood_device);
		FileUtil.saveWeightDevice(weight_device);
		FileUtil.saveTemputerDevice(temp_device);
	}

	public void loadData() {

	}

	public void initView() {

	}

	MyProgress myProgress;
	JSONObject msgBack = null;
	String TAG = "mainactivity";
	/**
	 * 返回
	 */
	private Handler responseHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			MLog.i(TAG, "back:" + msg.obj + "resuletCode:" + msg.arg1);
			myProgress.stop();
			if (null != msg.obj) {
				try {
					msgBack = new JSONObject(msg.obj.toString());
				} catch (JSONException e) {
					e.printStackTrace();
					btStartLogin();
				}
				if (msgBack.optInt("state") == ResultCode.SUCCESS) {
					int height = msgBack.optInt("height");
					MLog.i(TAG, "当前账户的height" + height);
					String userid = msgBack.optString("userid");
					int isregister = msgBack.optInt("isregister");

					MLog.i(TAG, "当前人的userid:" + userid + "当前人的isregister："
							+ isregister);
					if (height == 0) {

						Intent intent = new Intent(MainActivity.this,
								HeightActivity.class);
						intent.putExtra("userid", userid);
						MainActivity.this.startActivity(intent);

					} else if (isregister == 0) {
						Intent intent = new Intent(MainActivity.this,
								SetupAcValMobileActivity.class);
						intent.putExtra("userid", userid);
						MainActivity.this.startActivity(intent);
						finish();
					} else {
						Intent intent = new Intent(MainActivity.this,
								FragmentMainActivity.class);
						MainActivity.this.startActivity(intent);
						finish();
					}

				} else {
					String error = msgBack.optString("error");
					Toast.makeText(MainActivity.this, error, Toast.LENGTH_LONG)
							.show();
					if (error.contains("不存在")) {
						btStartExperience();
					} else {
						btStartLogin();
					}
					return;
				}
			} else {
				// setContentView(R.layout.start_main);
				btStartLogin();
			}
		}
	};

	// 封装Parser参数
	private Parser paramsParser;
	// 封装httpclient参数
	private HashMap<String, Object> params;
	private AsyncHttpClient asyncHttpClient;

	// 处理网络请求
	public void sendMsg() {
		myProgress = new MyProgress(this, 10);
		myProgress.start();
		paramsParser = new Parser();

		// 封装参数
		params = new HashMap<String, Object>();

		// 请求路径
		paramsParser.action = getString(R.string.login_bypwd);
		// 请求方式
		paramsParser.request = "post";

		// 请求参数
		params.put("phonenum", mobile);
		params.put("password", password);

		paramsParser.map = params;
		// 传递上下文
		paramsParser.context = MainActivity.this;

		asyncHttpClient = AsyncHttpClient.getInstance();
		asyncHttpClient.exeute(paramsParser, onResultListenerAdapter);
	}

	OnResultListenerAdapter onResultListenerAdapter = new OnResultListenerAdapter() {
		@Override
		public <T extends Parser> void onSuccess(T resultParser, int resultCode) {
			super.onSuccess(resultParser, resultCode);
			Message message = Message.obtain();
			message.arg1 = resultCode;
			message.obj = resultParser.back;
			responseHandler.sendMessage(message);
		}

		public <T extends Parser> void onFailure(T parserResult, int resultCode) {
			// setContentView(R.layout.start_main);
			btStartLogin();
		};
	};
	
	
	private Handler weightHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0x1101:
				break;

			default:
				break;
			}
		};
	};
	

	
}
